<template>
  <div class="agent-distributors">
    <div class="title-area">
      <h1>分销商管理</h1>
      
      <!-- 视图切换按钮组 -->
      <div class="view-toggle">
        <button 
          class="toggle-btn" 
          :class="{ active: viewType === 'card' }" 
          @click="setViewType('card')"
        >
          <i class="fas fa-th-large"></i> 卡片视图
        </button>
        <button 
          class="toggle-btn" 
          :class="{ active: viewType === 'table' }" 
          @click="setViewType('table')"
        >
          <i class="fas fa-table"></i> 表格视图
        </button>
      </div>
    </div>
    
    <!-- 操作区域 -->
    <div class="action-bar">
      <div class="search-filters">
        <div class="search-box">
          <i class="fas fa-search search-icon"></i>
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索分销商或联系人"
            @input="handleSearch"
          >
        </div>
        
        <div class="filter-group">
          <div class="filter-item">
            <label>状态</label>
            <select v-model="statusFilter" @change="handleFilterChange">
              <option value="">全部状态</option>
              <option value="active">活跃</option>
              <option value="pending">待审核</option>
              <option value="inactive">已禁用</option>
            </select>
          </div>
          
          <div class="filter-item">
            <label>等级</label>
            <select v-model="levelFilter" @change="handleFilterChange">
              <option value="">全部等级</option>
              <option value="1">初级分销商</option>
              <option value="2">中级分销商</option>
              <option value="3">高级分销商</option>
            </select>
          </div>
        </div>
      </div>
      
      <div class="action-buttons">
        <button class="export-btn" @click="handleExportData">
          <i class="fas fa-file-export"></i> 导出数据
        </button>
        <button class="create-btn" @click="handleCreateDistributor">
          <i class="fas fa-plus"></i> 创建分销商
        </button>
      </div>
    </div>
    
    <!-- 分销商视图区域 -->
    <DistributorTable 
      v-if="viewType === 'table'"
      :searchQuery="searchQuery"
      :statusFilter="statusFilter"
      :levelFilter="levelFilter"
      @view="handleViewDistributor"
      @edit="handleEditDistributor"
      @toggle-status="handleToggleStatus"
      @page-change="handlePageChange"
    />
    
    <!-- 分销商卡片网格 -->
    <div v-else class="distributor-grid">
      <DistributorCard
        v-for="distributor in filteredDistributors"
        :key="distributor.id"
        :distributor="distributor"
        @view="handleViewDistributor"
        @edit="handleEditDistributor"
        @toggle-status="handleToggleStatus"
      />
      
      <!-- 数据为空状态 -->
      <div v-if="filteredDistributors.length === 0" class="empty-state">
        <i class="fas fa-users-slash"></i>
        <p>{{ hasActiveFilters ? '未找到符合条件的分销商' : '暂无分销商数据' }}</p>
        <button v-if="hasActiveFilters" class="reset-btn" @click="resetFilters">重置筛选条件</button>
      </div>
    </div>
    
    <!-- 分页控制区 -->
    <div class="pagination-container" v-if="filteredDistributors.length > 0 && viewType === 'card'">
      <div class="pagination">
        <button class="pagination-btn" :disabled="currentPage <= 1" @click="handlePageChange(currentPage - 1)">
          <i class="fas fa-chevron-left"></i>
        </button>
        
        <div class="pagination-pages">
          <button 
            v-for="page in paginationPages" 
            :key="page"
            :class="['page-btn', { active: page === currentPage }]"
            @click="handlePageChange(page)"
          >
            {{ page }}
          </button>
        </div>
        
        <button class="pagination-btn" :disabled="currentPage >= totalPages" @click="handlePageChange(currentPage + 1)">
          <i class="fas fa-chevron-right"></i>
        </button>
      </div>
      
      <div class="page-info">
        显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, totalItems) }} 项，共 {{ totalItems }} 项
      </div>
    </div>
    
    <!-- 分销商表单模态框 -->
    <DistributorFormModal
      v-model:visible="formModalVisible"
      :is-edit="isEditMode"
      :distributor="currentDistributor"
      :commission-limits="{ min: 5, max: 30 }"
      @save="handleSaveDistributor"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import DistributorTable from '@/components/agent/distributors/DistributorTable.vue';
import DistributorCard from '@/components/agent/distributors/DistributorCard.vue';
import DistributorFormModal from '@/components/agent/distributors/DistributorFormModal.vue';
import { generateDistributorsData } from '@/utils/agentMock';

// 路由
const router = useRouter();

// 定义分销商类型
interface Distributor {
  id: string;
  name: string;
  avatar: string;
  commissionRate: number;
  totalSales: number;
  totalOrders: number;
  totalCommission: number;
  joinDate: string;
  status: 'active' | 'inactive' | 'pending';
  contactPerson?: string;
  phone?: string;
  email?: string;
  address?: string;
  level?: 'standard' | 'premium' | 'vip';
  remarks?: string;
}

// 视图类型
const viewType = ref<'card' | 'table'>('card'); // 默认为卡片视图

// 搜索和筛选状态
const searchQuery = ref('');
const statusFilter = ref('');
const levelFilter = ref('');

// 分销商数据
const distributors = ref<Distributor[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(9); // 每页9个卡片
const totalItems = ref(0);
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value));

// 分页显示的页码
const paginationPages = computed(() => {
  const pages = [];
  const maxVisiblePages = 5;
  
  if (totalPages.value <= maxVisiblePages) {
    // 如果总页数小于等于最大可见页数，则显示所有页码
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i);
    }
  } else {
    // 确定显示哪些页码
    let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
    let endPage = startPage + maxVisiblePages - 1;
    
    if (endPage > totalPages.value) {
      endPage = totalPages.value;
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
  }
  
  return pages;
});

// 模态框控制
const formModalVisible = ref(false);
const isEditMode = ref(false);
const currentDistributor = ref<Partial<Distributor>>({});

// 是否有活跃筛选条件
const hasActiveFilters = computed(() => {
  return !!searchQuery.value || !!statusFilter.value || !!levelFilter.value;
});

// 筛选后的分销商数据（用于卡片视图）
const filteredDistributors = computed(() => {
  let result = [...distributors.value];
  
  // 搜索功能
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(item => 
      item.name.toLowerCase().includes(query) || 
      (item.contactPerson && item.contactPerson.toLowerCase().includes(query)) ||
      item.id.toLowerCase().includes(query)
    );
  }
  
  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value);
  }
  
  // 等级筛选
  if (levelFilter.value) {
    const levelMap: Record<string, string> = {
      '1': 'standard',
      '2': 'premium',
      '3': 'vip'
    };
    result = result.filter(item => item.level === levelMap[levelFilter.value]);
  }
  
  // 更新总项目数
  totalItems.value = result.length;
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return result.slice(start, end);
});

// 设置视图类型
const setViewType = (type: 'card' | 'table') => {
  viewType.value = type;
  currentPage.value = 1; // 重置页码
};

// 处理搜索
const handleSearch = () => {
  console.log('搜索分销商:', searchQuery.value);
  currentPage.value = 1; // 重置页码
};

// 处理筛选变化
const handleFilterChange = () => {
  console.log('筛选条件变化:', { 
    status: statusFilter.value, 
    level: levelFilter.value 
  });
  currentPage.value = 1; // 重置页码
};

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
};

// 处理创建分销商
const handleCreateDistributor = () => {
  console.log('打开创建分销商模态框');
  isEditMode.value = false;
  currentDistributor.value = {
    commissionRate: 10,
    level: 'standard' as 'standard' | 'premium' | 'vip',
    status: 'active'
  };
  formModalVisible.value = true;
};

// 处理导出数据
const handleExportData = () => {
  console.log('导出分销商数据');
  // 实际项目中这里会触发数据导出功能
};

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = '';
  statusFilter.value = '';
  levelFilter.value = '';
  currentPage.value = 1; // 重置页码
};

// 处理表格/卡片组件事件
const handleViewDistributor = (distributor: Distributor) => {
  console.log('查看分销商详情:', distributor);
  // 导航到详情页面
  router.push(`/agent/distributors/${distributor.id}`);
};

const handleEditDistributor = (distributor: Distributor) => {
  console.log('打开编辑分销商模态框', distributor);
  isEditMode.value = true;
  currentDistributor.value = { ...distributor };
  formModalVisible.value = true;
};

const handleToggleStatus = (distributor: Distributor) => {
  // 切换状态
  const newStatus = distributor.status === 'active' ? 'inactive' : 'active';
  console.log(`切换分销商 ${distributor.name} 状态为 ${newStatus}`);
  
  // 更新本地数据
  const index = distributors.value.findIndex(d => d.id === distributor.id);
  if (index !== -1) {
    distributors.value[index].status = newStatus;
  }
};

// 处理保存分销商
const handleSaveDistributor = (distributorData: Partial<Distributor>) => {
  if (isEditMode.value && distributorData.id) {
    // 编辑现有分销商
    const index = distributors.value.findIndex(d => d.id === distributorData.id);
    if (index !== -1) {
      // 在真实项目中，这里应该是API调用
      distributors.value[index] = {
        ...distributors.value[index],
        ...distributorData
      } as Distributor;
      console.log('分销商已更新:', distributorData);
    }
  } else {
    // 创建新分销商
    // 在真实项目中，这里应该是API调用
    const newDistributor = {
      id: `dist_${Math.floor(Math.random() * 10000)}`,
      avatar: `https://i.pravatar.cc/150?img=${Math.floor(Math.random() * 70)}`,
      totalSales: 0,
      totalOrders: 0,
      totalCommission: 0,
      joinDate: new Date().toISOString().split('T')[0],
      ...distributorData
    } as Distributor;
    
    distributors.value.unshift(newDistributor);
    console.log('新分销商已创建:', newDistributor);
  }
  
  formModalVisible.value = false;
};

// 生命周期钩子
onMounted(() => {
  // 加载分销商数据
  distributors.value = generateDistributorsData(30) as unknown as Distributor[];
  totalItems.value = distributors.value.length;
});
</script>

<style lang="scss" scoped>
.agent-distributors {
  padding: 28px;
  max-width: 100%;
  
  .title-area {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h1 {
      font-size: 24px;
      font-weight: 600;
      color: #1e293b;
      margin: 0;
      position: relative;
      
      &:after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 0;
        width: 40px;
        height: 3px;
        background: linear-gradient(90deg, #3b82f6, #38bdf8);
        border-radius: 3px;
      }
    }
    
    .view-toggle {
      display: flex;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
      
      .toggle-btn {
        padding: 10px 16px;
        background-color: #fff;
        border: 1px solid #e2e8f0;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 14px;
        color: #64748b;
        transition: all 0.2s;
        
        &:first-child {
          border-right: none;
          border-radius: 8px 0 0 8px;
        }
        
        &:last-child {
          border-radius: 0 8px 8px 0;
        }
        
        &:hover {
          background-color: #f8fafc;
        }
        
        &.active {
          background-color: #3b82f6;
          color: #fff;
          border-color: #3b82f6;
        }
      }
    }
  }
  
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    gap: 16px;
    flex-wrap: wrap;
    
    .search-filters {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      flex: 1;
      min-width: 280px;
    }
    
    .search-box {
      position: relative;
      flex: 1;
      min-width: 280px;
      
      input {
        width: 100%;
        padding: 10px 16px 10px 42px;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        font-size: 14px;
        transition: all 0.2s;
        color: #1e293b;
        background-color: #fff;
        height: 44px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        
        &::placeholder {
          color: #94a3b8;
        }
        
        &:focus {
          outline: none;
          border-color: #3b82f6;
          box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
      }
      
      .search-icon {
        position: absolute;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
        color: #94a3b8;
      }
    }
    
    .filter-group {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
      
      .filter-item {
        display: flex;
        flex-direction: column;
        gap: 4px;
        min-width: 160px;
        
        label {
          font-size: 13px;
          color: #64748b;
          font-weight: 500;
        }
        
        select {
          padding: 0 12px;
          height: 44px;
          border-radius: 8px;
          border: 1px solid #e2e8f0;
          background-color: #fff;
          font-size: 14px;
          color: #1e293b;
          appearance: none;
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%2364748b'%3E%3Cpath fill-rule='evenodd' d='M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z' clip-rule='evenodd'/%3E%3C/svg%3E");
          background-position: right 12px center;
          background-size: 16px;
          background-repeat: no-repeat;
          transition: all 0.2s;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
          
          &:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
          }
        }
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 12px;
      
      button {
        height: 44px;
        border-radius: 8px;
        padding: 0 18px;
        font-size: 14px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 8px;
        border: none;
        cursor: pointer;
        transition: all 0.2s;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        white-space: nowrap;
        
        i {
          font-size: 14px;
        }
      }
      
      .export-btn {
        background-color: #fff;
        color: #64748b;
        border: 1px solid #e2e8f0;
        
        &:hover {
          background-color: #f8fafc;
          color: #3b82f6;
          border-color: #cbd5e1;
        }
      }
      
      .create-btn {
        background-color: #3b82f6;
        color: #fff;
        
        &:hover {
          background-color: #2563eb;
        }
      }
    }
  }
  
  .distributor-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
    gap: 24px;
    margin-bottom: 24px;
    position: relative;
    min-height: 300px;
  }
  
  .empty-state {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 16px;
    
    i {
      font-size: 48px;
      color: #cbd5e1;
    }
    
    p {
      font-size: 16px;
      color: #64748b;
      margin: 0;
    }
    
    .reset-btn {
      padding: 8px 16px;
      border-radius: 6px;
      border: none;
      background-color: #3b82f6;
      color: #fff;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background-color: #2563eb;
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    margin-top: 12px;
    flex-wrap: wrap;
    gap: 16px;
    
    .pagination {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .pagination-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36px;
        height: 36px;
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        background-color: #fff;
        color: #64748b;
        cursor: pointer;
        transition: all 0.2s;
        
        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
        
        &:not(:disabled):hover {
          border-color: #cbd5e1;
          background-color: #f8fafc;
        }
      }
      
      .pagination-pages {
        display: flex;
        gap: 8px;
        
        .page-btn {
          width: 36px;
          height: 36px;
          border-radius: 8px;
          border: 1px solid #e2e8f0;
          background-color: #fff;
          color: #64748b;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &:hover {
            border-color: #cbd5e1;
            background-color: #f8fafc;
          }
          
          &.active {
            background-color: #3b82f6;
            color: #fff;
            border-color: #3b82f6;
          }
        }
      }
    }
    
    .page-info {
      font-size: 14px;
      color: #64748b;
    }
  }
}

@media (max-width: 768px) {
  .agent-distributors {
    padding: 20px;
    
    .title-area {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
      
      .view-toggle {
        width: 100%;
        
        .toggle-btn {
          flex: 1;
          justify-content: center;
        }
      }
    }
    
    .action-bar {
      flex-direction: column;
      
      .search-filters {
        width: 100%;
      }
      
      .action-buttons {
        width: 100%;
        
        button {
          flex: 1;
          justify-content: center;
        }
      }
    }
    
    .distributor-grid {
      grid-template-columns: 1fr;
    }
    
    .pagination-container {
      flex-direction: column-reverse;
      align-items: center;
      
      .pagination {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style> 